package com.vs.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.vs.model.CustomMessage;
import com.vs.util.Constants;

public class CustomFilter implements Filter {

	FilterConfig filterConfig = null;

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {

		/*
		 * servletResponse.setContentType("text/html");
		 * 
		 * PrintWriter out = servletResponse.getWriter();
		 * out.println("my-param (InitParameter): " +
		 * filterConfig.getInitParameter("my-param"));
		 * out.println("<br/><br/>Parameters:<br/>"); Enumeration<String>
		 * parameterNames = servletRequest.getParameterNames(); if
		 * (parameterNames.hasMoreElements()) { while
		 * (parameterNames.hasMoreElements()) { String name =
		 * parameterNames.nextElement(); String value =
		 * servletRequest.getParameter(name); System.out.println("name:" + name
		 * + ", value: " + value + "<br/>"); } } else {
		 * System.out.println("---None---<br/>"); }
		 * out.println("<br/>Start Regular Content:<br/><hr/>");
		 * filterChain.doFilter(servletRequest, servletResponse);
		 * out.println("<br/><hr/>End Regular Content:<br/>");
		 */

		String excludePath = filterConfig.getInitParameter("exclude");
		System.out.println("excludePath=" + excludePath);
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;

		ArrayList<CustomMessage> customErrors = new ArrayList<CustomMessage>();

		HttpSession session = request.getSession(false);
		String path = ((HttpServletRequest) request).getRequestURI();
		System.out.println("path=" + path);
		if (session == null && !path.contains(excludePath)) {
			CustomMessage info = new CustomMessage();
			info.setMessageLevel(Constants.ERROR);
			info.setMessageText("User session has been expired, Please login again");
			customErrors.add(info);
			request.setAttribute("customErrors", customErrors);
			response.sendRedirect("login.jsp");
		} else {
			filterChain.doFilter(servletRequest, servletResponse);
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

}
